﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Tradier.Models;
using System.Globalization;
using RestSharp;
using Newtonsoft.Json.Linq;

namespace Tradier
{
    public partial class OrdersHistory : System.Web.UI.Page
    {
        public Dictionary<int, List<OrderHistoryModel>> Orders { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            var accessToken = Session["UserTradierAccessToken"];
            if (accessToken == null)
            {
                Response.Redirect("/login.aspx");
            }
            GetUserOrders((string)accessToken);
        }

        private void GetUserOrders(string accessToken)
        {
            try
            {
                var client = new RestClient("https://api.tradier.com");
                var request = new RestRequest("/v1/user/history", Method.GET);

                request.AddHeader("Authorization", "Bearer " + accessToken);
                var result = (client.Execute(request).Content);
                var json = JObject.Parse(result);

                Orders = CreateMapping(json);
            }
            catch
            {

            }
        }

        private Dictionary<int, List<OrderHistoryModel>> CreateMapping(JObject json)
        {
            var orderModel = new Dictionary<int, List<OrderHistoryModel>>();
            var accountOrders = new List<OrderHistoryModel>();

            var accounts = json["accounts"]["account"];
            if (accounts.GetType().Name == "JArray")
            {
                foreach (JObject account in accounts)
                {
                    accountOrders = new List<OrderHistoryModel>();
                    if (account["history"].HasValues)
                    {
                        var orders = account["history"]["event"];
                        var accountNumber = (int)account["account_number"];

                        if (orders.GetType().Name == "JArray")
                        {
                            foreach (var order in orders)
                            {
                                string type = (string)order["type"];
                                var orderItem = new OrderHistoryModel()
                                {
                                    Amount = (float)order["amount"],
                                    Type = type,
                                    Date = DateTime.ParseExact((string)order["date"], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                    Commission = order[type]["commission"] != null ? (float)order[type]["commission"] : 0,
                                    Description = order[type]["description"] != null ? (string)order[type]["description"] : "",
                                    Price = order[type]["price"] != null ? (float)order[type]["price"] : 0,
                                    Quantity = order[type]["quantity"] != null ? (int)order[type]["quantity"] : 0,
                                    Symbol = order[type]["symbol"] != null ? (string)order[type]["symbol"] : "",
                                    TradeType = order[type]["trade_type"] != null ? (string)order[type]["trade_type"] : ""
                                };
                                accountOrders.Add(orderItem);
                            }
                        }
                        else
                        {
                            var order = orders;
                            string type = (string)order["type"];
                            var orderItem = new OrderHistoryModel()
                            {
                                Amount = (float)order["amount"],
                                Type = type,
                                Date = DateTime.ParseExact((string)order["date"], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                Commission = order[type]["commission"] != null ? (float)order[type]["commission"] : 0,
                                Description = order[type]["description"] != null ? (string)order[type]["description"] : "",
                                Price = order[type]["price"] != null ? (float)order[type]["price"] : 0,
                                Quantity = order[type]["quantity"] != null ? (int)order[type]["quantity"] : 0,
                                Symbol = order[type]["symbol"] != null ? (string)order[type]["symbol"] : "",
                                TradeType = order[type]["trade_type"] != null ? (string)order[type]["trade_type"] : ""
                            };
                            accountOrders.Add(orderItem);
                        }
                        orderModel.Add(accountNumber, accountOrders);
                    }
                }
            }
            else
            {
                if (accounts["history"].HasValues)
                {
                    var orders = accounts["history"]["event"];
                    var accountNumber = (int)accounts["account_number"];
                    accountOrders = new List<OrderHistoryModel>();

                    if (orders.GetType().Name == "JArray")
                    {
                        foreach (var order in orders)
                        {
                            string type = (string)order["type"];
                            var orderItem = new OrderHistoryModel()
                            {
                                Amount = (float)order["amount"],
                                Type = type,
                                Date = DateTime.ParseExact((string)order["date"], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                Commission = order[type]["commission"] != null ? (float)order[type]["commission"] : 0,
                                Description = order[type]["description"] != null ? (string)order[type]["description"] : "",
                                Price = order[type]["price"] != null ? (float)order[type]["price"] : 0,
                                Quantity = order[type]["quantity"] != null ? (int)order[type]["quantity"] : 0,
                                Symbol = order[type]["symbol"] != null ? (string)order[type]["symbol"] : "",
                                TradeType = order[type]["trade_type"] != null ? (string)order[type]["trade_type"] : ""
                            };
                            accountOrders.Add(orderItem);
                        }
                    }
                    else
                    {
                        var order = orders;
                        string type = (string)order["type"];
                        var orderItem = new OrderHistoryModel()
                        {
                            Amount = (float)order["amount"],
                            Type = type,
                            Date = DateTime.ParseExact((string)order["date"], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                            Commission = order[type]["commission"] != null ? (float)order[type]["commission"] : 0,
                            Description = order[type]["description"] != null ? (string)order[type]["description"] : "",
                            Price = order[type]["price"] != null ? (float)order[type]["price"] : 0,
                            Quantity = order[type]["quantity"] != null ? (int)order[type]["quantity"] : 0,
                            Symbol = order[type]["symbol"] != null ? (string)order[type]["symbol"] : "",
                            TradeType = order[type]["trade_type"] != null ? (string)order[type]["trade_type"] : ""
                        };
                        accountOrders.Add(orderItem);
                    }
                    orderModel.Add(accountNumber, accountOrders);
                }
            }

            return orderModel;
        }
    }
}